package com.zhupf.part7;

import java.util.HashSet;
import java.util.Set;

/**
 * @author zhupf
 * @date 2023年11月08日 16:57
 * @Description
 */
public class GetIntersectionNode {

    public static void main(String[] args) {

    }

    public static ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        Set<ListNode> set = new HashSet<>();
        ListNode node = headA;
        do {
            set.add(node);
        } while ((node = node.next) != null);
        do {
            if (set.contains(headB)) {
                return headB;
            }
        } while ((headB = headB.next) != null);
        return null;
    }

    public static ListNode getIntersectionNode2(ListNode headA, ListNode headB) {
        ListNode a = headA, b = headB;
        while (a != b) {
            a = a == null ? headB : a.next;

            b = b == null ? headA : b.next;
        }
        return a;
    }
}

class ListNode {
    int val;
    ListNode next;

    ListNode(int x) {
        val = x;
        next = null;
    }
}
